from datetime import datetime
import hashlib
from flask import json
from exts import db
from sqlalchemy.dialects.mysql import JSON
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import func
from models.user import AdminUser, RoleType


class user_service:
    # 返回标准的用户信息
    def get_user_info(self, user_id):
        if not user_id:
            raise Exception("用户ID不能为空")
        user = AdminUser.query.filter_by(id=user_id).first()
        if user:
            return {
                "id": user.id,
                "username": user.username,
                "role_type": user.role_type.value,
                "created_at": user.created_at.isoformat(),
            }
        else:
            raise Exception(f"用户{user_id}不存在")

    def get_all_users(self):
        users = AdminUser.query.all()
        return [
            {
                "id": user.id,
                "username": user.username,
                "role_type": user.role_type.value,
                "created_at": user.created_at.isoformat(),
            }
            for user in users
        ]

    # 获取用户是否已经存在
    def get_user_by_username(self, username):
        return AdminUser.query.filter_by(username=username).first()

    def create_user(self, post_json):
        if post_json:
            username = post_json.get("username")
            password = post_json.get("password")
            role_type = post_json.get("role_type")

            if not username or not password or not role_type:
                raise Exception("用户名、密码、角色类型不能为空")

            if self.get_user_by_username(username):
                raise Exception(f"用户名 {username} 已存在")

            try:
                role_type = RoleType(role_type)
            except ValueError:
                raise Exception(f"无效的角色类型 {role_type}，有效的角色类型为 {[role.value for role in RoleType]}")

            # 创建新用户
            new_user = AdminUser(
                username=username,
                password_hash=generate_password_hash(password),
                role_type=role_type,
            )
            db.session.add(new_user)
            db.session.commit()

            return self.get_user_info(new_user.id)

    def update_user(self, put_json):
        if put_json:
            user_id = put_json.get("id")
            username = put_json.get("username", None)
            password = put_json.get("password", None)
            role_type = put_json.get("role_type", None)

            if not user_id:
                raise Exception("用户ID不能为空")

            if not self.get_user_info(user_id):
                raise Exception(f"用户 {user_id} 不存在")

            user = AdminUser.query.get(user_id)
            if username:
                user.username = username
            if password:
                user.password_hash = generate_password_hash(password)
            if role_type:
                try:
                    # 检查 role_type 是否为有效的 RoleType 枚举值
                    role_type = RoleType(role_type)
                    user.role_type = role_type
                except ValueError:
                    raise Exception(f"无效的角色类型 {role_type}，有效的角色类型为 {[role.value for role in RoleType]}")
            db.session.commit()
            return self.get_user_info(user_id)

    def delete_user(self, delete_json):
        if delete_json:
            user_id = delete_json.get("id")
            if not user_id:
                raise Exception("用户ID不能为空")

            user = AdminUser.query.get(user_id)
            if not user:
                raise Exception(f"用户 {user_id} 不存在")

            # 先获取用户信息保存
            user_info = self.get_user_info(user_id)

            db.session.delete(user)
            db.session.commit()
            return user_info  # 返回删除前的用户信息
